package com.minelx.sequence.core;

import com.minelx.sequence.pattern.PrefixMatcher;

import java.util.LinkedList;
import java.util.List;

public class JoinMatcher<E> implements ReturnMatcher<List<E>, StringScanner> {
	private final ReturnMatcher<String, StringScanner> joinerMatcher;

	private final ReturnMatcher<E, StringScanner> elementMatcher;

	public JoinMatcher(ReturnMatcher<String, StringScanner> joinerMatcher,
	                   ReturnMatcher<E, StringScanner> elementMatcher) {
		this.joinerMatcher = joinerMatcher;
		this.elementMatcher = elementMatcher;
	}

	@Override
	public boolean isMatch(StringScanner clue) {
		return elementMatcher.isMatch(clue);
	}

	@Override
	public List<E> onMatched(StringScanner clue) {
		List<E> result = new LinkedList<>();
		// add first element
		result.add(elementMatcher.get(clue).orElseThrow(RuntimeException::new));
		// add elements behind joiners
		clue.stream(new PrefixMatcher<>(joinerMatcher, elementMatcher))
				.forEach(result::add);
		return result;
	}
}
